package com.abcode.design.behaviour.observer.demo;

import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;

/**
 * 基础发布者
 *
 * @author qinzhitao
 * @date 2023/4/10 9:31
 */
public class EventManager {
    Map<String, List<EventListener>> listenerMap = new HashMap<>();

    public EventManager(String... eventTypeArr) {
        for (String eventType : eventTypeArr) {
            this.listenerMap.put(eventType, new ArrayList<>());
        }
    }

    /**
     * 订阅
     * @param eventType
     * @param listener
     */
    public void subscribe(String eventType, EventListener listener){
        List<EventListener> eventListenerList = listenerMap.get(eventType);
        if(CollectionUtils.isEmpty(eventListenerList)){
            eventListenerList = new ArrayList<>();
            eventListenerList.add(listener);
            listenerMap.put(eventType, eventListenerList);
        }else{
            eventListenerList.add(listener);
        }
    }

    /**
     * 取消订阅
     * @param eventType
     * @param listener
     */
    public void unsubscribe(String eventType, EventListener listener){
        List<EventListener> eventListenerList = listenerMap.get(eventType);
        if(!CollectionUtils.isEmpty(eventListenerList)){
            eventListenerList.remove(listener);
        }
    }

    /**
     * 事件通知
     * @param eventType
     * @param file
     */
    public void notify(String eventType, File file){
        List<EventListener> eventListenerList = listenerMap.get(eventType);
        for (EventListener eventListener : eventListenerList) {
            eventListener.update(eventType, file);
        }
    }
}
